/**
 * @p.md
 * 
 * mailboxFactory 模块，提供创建邮箱的工厂函数
 */
import { Mailbox, MessageQueue, DefaultMessageQueue } from './mailbox';
import { DefaultMailbox } from './defaultMailbox';
import { Mailbox as MailboxProps } from './props';

/**
 * 创建默认邮箱
 */
export function createDefaultMailbox(): Mailbox {
  // 创建一个简单的默认邮箱实现，包含所需的方法
  const userMessages: any[] = [];
  const systemMessages: any[] = [];
  let invoker: any = null;
  let dispatcher: any = null;
  
  return {
    postMessage(message: any): void {
      userMessages.push(message);
      processMessages();
    },
    
    postSystemMessage(message: any): void {
      systemMessages.push(message);
      processMessages();
    },
    
    registerHandlers(inv: any, disp: any): void {
      invoker = inv;
      dispatcher = disp;
    },
    
    start(): void {
      processMessages();
    }
  };
  
  function processMessages() {
    if (!invoker || !dispatcher) return;
    
    // 处理系统消息
    while (systemMessages.length > 0) {
      const msg = systemMessages.shift();
      if (msg) {
        dispatcher.schedule(() => {
          if (invoker.invokeSystemMessage) {
            invoker.invokeSystemMessage(invoker._actor, msg);
          }
        });
      }
    }
    
    // 处理用户消息
    while (userMessages.length > 0) {
      const msg = userMessages.shift();
      if (msg) {
        dispatcher.schedule(() => {
          if (invoker.invokeUserMessage) {
            invoker.invokeUserMessage(invoker._actor, msg);
          }
        });
      }
    }
  }
}

/**
 * 创建自定义邮箱
 * @param userMailbox 用户消息队列
 * @param systemMailbox 系统消息队列
 */
export function createCustomMailbox(
  userMailbox: MessageQueue, 
  systemMailbox: MessageQueue
): Mailbox {
  return new DefaultMailbox(userMailbox, systemMailbox);
}

/**
 * 创建无界邮箱
 */
export function createUnboundedMailbox(): Mailbox {
  return createDefaultMailbox();
}

/**
 * 创建有界邮箱
 * @param capacity 容量限制
 */
export function createBoundedMailbox(capacity: number): Mailbox {
  // 在实际实现中，这里应该创建容量受限的消息队列
  // 由于我们还没有实现有界消息队列，这里使用默认队列
  console.warn(`[MailboxFactory] Bounded mailbox with capacity ${capacity} not implemented, using unbounded mailbox`);
  return createDefaultMailbox();
} 